/**
 *
 * 用于存放公共的功能函数
 *
 */
import moment from 'moment/moment';

/**
 * 生成query字符串
 * @param obj
 * @returns {string}
 */
export function genQuery(obj) {
  let index = 0;
  let query = '';
  Object.keys(obj).forEach((name) => {
    if (obj[name] !== undefined && obj[name] !== null) {
      if (index !== 0) {
        query += '&';
      }
      //const value = obj[name];
      const value = typeof obj[name] === 'string' ? encodeURIComponent(obj[name]) : obj[name];
      query += `${name}=${value}`;
      index += 1;
    }
  });
  return query;
}

/**
 * @param name 希望获取的query项
 * @returns 对应的query值
 */
export function getQueryString(name) {
  const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`, 'i');
  const r = window.location.search.substr(1).match(reg);
  if (r != null) {
    return unescape(r[2]);
  }
  return null;
}

/**
 * 数组去重
 * @param arr
 * @returns {Array}
 */
export function unique(arr) {
  const newArr = [];
  for (let i = 0; i < arr.length; i++) {
    if (newArr.indexOf(arr[i]) === -1) {
      newArr.push(arr[i]);
    }
  }
  return newArr;
}

/**
 * 生成UUid
 * @returns {string}
 */
/* eslint-disable */
export function generateUUID() {
  let d = new Date().getTime();
  const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    let r = (d + Math.random() * 16) % 16 | 0;
    d = Math.floor(d/16);
    return (c=='x' ? r : (r&0x7|0x8)).toString(16);
  });
  return uuid;
}
/* eslint-enable */

const TIME_FORMAT = 'YYYY/MM/DD';
export function formatUtcTime(timeSecond, dstFormat) {
  const outformat = dstFormat || TIME_FORMAT;
  return moment.utc(timeSecond).format(outformat);
}

// 根据数组中对象的key值找到对应的value
export function getArrayValue(array, arrayKey) {
  const name = [];
  arrayKey.forEach((value) => {
    array.forEach((value2) => {
      if (value2.id === parseInt(value, 10)) {
        name.push(value2.name);
      }
    });
  });
  return name;
}
